package org.carl.nginx.main;

import cn.hutool.core.io.watch.SimpleWatcher;
import cn.hutool.core.io.watch.WatchMonitor;
import cn.hutool.core.io.watch.watchers.DelayWatcher;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import org.carl.nginx.core.NginxConfig;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.util.logging.Logger;

public class Watcher {
    public static Logger LOGGER = Logger.getGlobal();
    public static String execPath = NginxConfig.getExecPath();
    public static String nginxHome = NginxConfig.getNginxHome();
    public static String execPrefix = NginxConfig.getExecPrefix();
    public static String execCmd = execPrefix + " cd " + nginxHome + " && " + execPath + " -s reload";

    public static void main(String[] args) {
        String[] scanDir = NginxConfig.getScanDir();
        for (String dir : scanDir) {
            File file = new File(nginxHome + File.separator + dir);
            LOGGER.info(StrUtil.format("Start Listener {} folder", file.getPath()));
            WatchMonitor monitor = WatchMonitor.createAll(file, new DelayWatcher(new ReloadWatcher(), 500));
            monitor.setMaxDepth(5);
            monitor.start();
        }
    }

    static class ReloadWatcher extends SimpleWatcher {
        @Override
        public void onCreate(WatchEvent<?> event, Path currentPath) {
            LOGGER.info(StrUtil.format("File/Folder{} Created,Refresh nginx", currentPath.toString()));
            RuntimeUtil.execForStr(execCmd);
        }
        @Override
        public void onModify(WatchEvent<?> event, Path currentPath) {
            LOGGER.info(StrUtil.format("File/Folder{} Modify,Refresh nginx", currentPath.toString()));
            RuntimeUtil.execForStr(execCmd);
        }
        @Override
        public void onDelete(WatchEvent<?> event, Path currentPath) {
            LOGGER.info(StrUtil.format("File/Folder{} Deleted,Refresh nginx", currentPath.toString()));
            RuntimeUtil.execForStr(execCmd);
        }
    }
}

